package edu.gatech.gitmad.catbug.formation;

import java.util.HashMap;
import java.util.Scanner;

public class GroupData {	
	public static final long DOWNLOAD_DELAY = 30000;
	private HashMap<String, MemberData> data;
	private boolean receiving;
	private Thread thread;
	private UpdateGetter updateGetter;
	
	public GroupData() {
		data = new HashMap<String, MemberData>();
		receiving = false;
		updateGetter = new UpdateGetter();
	}
	
	@SuppressWarnings("unchecked")
	public HashMap<String, MemberData> getData() {
		return (HashMap<String, MemberData>)data.clone();
	}
	
	public void forceUpdate() {
		updateGetter.getUpdate();
	}
	
	public void startReceiving() {
		if (!receiving) {
			receiving = true;
			thread = new Thread(updateGetter);
			thread.start();
		}
	}
	
	public void stopReceiving() {
		receiving = false;
		if (thread != null) {
			thread.interrupt();
		}
	}
	
	
	private class UpdateGetter implements Runnable {
		
		public void getUpdate() {
			HTTPGet get = new HTTPGet(SessionData.databaseurl + String.format("/getupdate?Group=%s", SessionData.getGroupID()));
			String res = get.getHTML();
			Scanner scan = new Scanner(res);
			while (scan.hasNext()) {
				String line = scan.next();
				if (line.equals("tittyballs")) {
					break;
				}
				String[] split = line.split(" ");
				
				if (split.length == 3) {
					String ID = split[0];
					String name = split[1];
					double lat = 0.0;
					double lon = 0.0;
					boolean valid = false;
					try {
						lat = Double.parseDouble(split[2]);
						lon = Double.parseDouble(split[3]);
						valid = true;
					}
					catch (NumberFormatException e) {
						
					}
					if (valid) {
						MemberData coord = data.get(ID);
						if (coord == null) {
							data.put(ID, new MemberData(name, lat, lon));
						}
						else {
							coord.setLatLon(lat, lon);
							coord.setName(name);
						}
					}
				}
			}
			scan.close();
		}
		
		public void run() {
			while (receiving) {
				getUpdate();
				try {
					Thread.sleep(DOWNLOAD_DELAY);
				}
				catch (InterruptedException e) {
					
				}
			}
		}
	}
	
}
